import { useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

export default function AskPost({ postId }: { postId: string }) {
  const [query, setQuery] = useState("");
  const [answer, setAnswer] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);

  const handleAsk = () => {
    if (!query.trim()) return;

    setAnswer("");
    setIsStreaming(true);

    const eventSource = new EventSource(
      `/api/posts/${postId}/ask/stream?query=${encodeURIComponent(query)}`
    );

    eventSource.addEventListener("message", (e) => {
      setAnswer((prev) => prev + e.data);
    });

    eventSource.onerror = () => {
      eventSource.close();
      setIsStreaming(false);
    };
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 max-w-2xl mx-auto my-8">
      <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Ask AI about this post</h2>
      <div className="flex items-center space-x-2 mb-4">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          className="block w-full rounded-md border-0 py-2.5 px-3 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6 dark:bg-white/5 dark:text-white dark:ring-white/10 dark:focus:ring-indigo-500"
          placeholder="Ask a question about this post..."
          disabled={isStreaming}
        />
        <button
          onClick={handleAsk}
          disabled={isStreaming}
          className={`px-6 py-3 rounded-lg font-semibold text-white transition-colors ${
            isStreaming
              ? 'bg-gray-400 dark:bg-gray-600 cursor-not-allowed'
              : 'bg-indigo-600 hover:bg-indigo-700 dark:bg-indigo-500 dark:hover:bg-indigo-600'
          }`}
        >
          Ask
        </button>
      </div>

      <div className="bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg p-4 h-80 overflow-y-auto">
        {answer ? (
          <ReactMarkdown remarkPlugins={[remarkGfm]} className="prose dark:prose-invert max-w-none">
            {answer}
          </ReactMarkdown>
        ) : (
          <p className="text-gray-500 dark:text-gray-400 italic">
            Ask any question about this post...
          </p>
        )}
        {isStreaming && (
          <div className="flex items-center space-x-2 text-gray-600 dark:text-gray-400 animate-pulse mt-4">
            <div className="w-2 h-2 bg-indigo-500 rounded-full"></div>
            <div className="w-2 h-2 bg-indigo-500 rounded-full animation-delay-200"></div>
            <div className="w-2 h-2 bg-indigo-500 rounded-full animation-delay-400"></div>
            <span>AI is thinking...</span>
          </div>
        )}
      </div>
    </div>
  );
}
